import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import { routerRedux, Route, Switch } from 'dva/router';
import Media from 'react-media';
import AdSelect from '@/components/AdSelect';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Drawer,
} from 'antd';
import AdSearch from '@/components/AdSearch';
import AdButton from '@/components/AdButton';
import { codes } from './utils';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import OilCardDetails from './OilCardDetails';
import SelectForm from '@/components/SelectForm';
import ManageList from '@/components/ManageList';
import TableButtons from '@/components/TableButtons';
import RightDraw from '@/components/RightDraw';
import prompt from '@/components/Prompt';
import RechargeForm from './RechargeForm';
import SearchSelect from '@/components/SearchSelect';
import { columns1 } from '@/pages/Common/common';
import { formateDateToMin } from '@/utils/common';

const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;
const confirm = Modal.confirm;

@ManageList
@connect(({ tmsOilCard, common, component, loading }) => ({
  tmsOilCard,
  
  searchValue: component.searchValue,
  ownCompany: common.ownCompany,
  loading: loading.effects['tmsOilCard/selectList'],
  dictObject: common.dictObject,
}))
@Form.create()
export default class OilCardList extends Component {
  state = {
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    stepFormValues: {},
    visible: false,
    rechargeVisible: false,
    checkId: '',
    checkIds: [],
    formValues: {},
    vehicleAbled: '',
    cardNo: '',
    cars: [],
  };
  className = 'OilCardList';
  columns = [
    {
      title: '卡号',
      dataIndex: 'cardNo',
      render: (text, record) => (
        <AdButton
          mode="a"
          onClick={e => this.showDetail(e, record)}
          text={text}
          code={codes.showDetail}
        />
      ),
      fixed: this.props.isMobile ? false : true,
    },
    {
      title: '车辆',
      dataIndex: 'cartPlateNo',
    },
    {
      title: '类型',
      dataIndex: 'cardType',
      render: text => (
      <AdSelect onlyRead={true} value={text} data={this.props.dictObject['CARD_TYPE']} />
      ),
    },
    {
      title: '发售公司',
      dataIndex: 'sellCompanyCode',
    },
    {
      title: '所属公司',
      dataIndex: 'ownCompanyName',
      width: 250,
      render: text => <span title={text}>{text}</span>,
    },
    {
      title: '币种',
      dataIndex: 'currencyType',
      render: text => (
        <AdSelect onlyRead={true} value={text} data={this.props.dictObject['currency-type']} />
      ),
      width: 100,
    },
    {
      title: '剩余金额',
      dataIndex: 'currentMoney',
    },
    {
      title: '状态',
      dataIndex: 'beActive',
      render: (text, record) => <span>{text ? '启用' : '禁用'}</span>,
      width: 100,
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      render: text => (
        <AdSearch
          label="loginName"
          name="sysName"
          value={this.props.searchValue[text]}
          onlyRead={true}
        />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
    },
    {
      title: '更新人',
      dataIndex: 'updateBy',
      render: text => (
        <AdSearch
          label="loginName"
          name="sysName"
          value={this.props.searchValue[text]}
          onlyRead={true}
        />
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
    },
  ];
  componentDidMount() {
   // console.log('油卡管理--common-',this.props.common,'dictObject',this.props.dictObject)
    this.getSelectList();
    // 查询字典：
    // 发售公司
    this.props.dispatch({
      type: 'common/querytDictByCode',
      payload: { code: 'sale-company' },
    });
    this.props.dispatch({
      type: 'common/querytDictByCode',
      payload: { code: 'currency-type' },
    });
    this.props.dispatch({
      type: 'common/querytDictByCode',
      payload: { code: 'CARD_TYPE' },
    });
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.dictObject['sale-company'] && nextProps.tmsOilCard.selectList.list) {
      nextProps.dictObject['sale-company'].map(v => {
        nextProps.tmsOilCard.selectList.list.map((v1, i1) => {
          if (v.code === v1.sellCompanyCode) {
            nextProps.tmsOilCard.selectList.list[i1].sellCompanyCode = v.value;
          }
        });
      });
    }
  }

  onRef = ref => {
    this.child = ref;
  };

  getSelectList = val => {
    const { dispatch, searchValue } = this.props;
    let params = val || {};
    dispatch({
      type: 'tmsOilCard/selectList',
      payload: params,
      callback: data => {
        if (!data) return;
        let valueList = [];
        data.map(v => {
          const labels = ['updateBy', 'createBy'];
          labels.map(item => {
            if (v[item] && !valueList.includes(v[item])) {
              valueList.push(v[item]);
              !searchValue[v[item]] &&
                dispatch({
                  type: 'component/querySearchValue',
                  payload: {
                    params: { loginName: v[item] },
                    url: 'tms/tms-oil-card/selectOilUser_s',
                  },
                });
            }
          });
        });
      },
    });
  };

  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
      cars: [],
    });
    this.getSelectList();
  };

  toggleForm = expandForm => {
    this.setState({
      expandForm,
    });
  };

  handleSelectRows = rows => {
    // console.log('选择', rows);
    let ids = [];
    if (Array.isArray(rows) && rows.length > 0) {
      rows.map((item, i) => {
        ids.push(item.id);
      });
    }
    this.setState({
      selectedRows: rows,
      checkIds: ids,
    });
  };

  //查询
  handleSearch = values => {
    // if (!values) {
    //   return;
    // }
    const { ...value } = values;
    const { cars } = this.state;
    if (cars.length > 0) {
      const vehicleId = cars.map(v => {
        return v.id;
      });
      value.vehicleId = vehicleId.join(',');
    } else {
      value.vehicleId = '';
    }
    this.setState({
      formValues: value,
    });
    this.getSelectList(value);
  };

  //新建
  handleAdd = () => {
    const { dispatch } = this.props;
    router.push(`/carBasic/oilCardList/add-form`);
  };
  //编辑：
  handleEdit = () => {
    router.push(`/carBasic/oilCardList/edit-form/${this.state.checkId}`);
    this.closeDetail();
  };
  // 分页操作：改参数
  handleStandardTableChange = param => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const params = {
      ...formValues,
      ...param,
    };

    this.getSelectList(params);
  };

  //详情：
  showDetail = (e, record) => {
    e.stopPropagation();
    const { dispatch } = this.props;
    const { id, cardNo } = record;
    dispatch({
      type: 'tmsOilCard/selectDetails',
      payload: { id: id },
    });
    dispatch({
      type: 'tmsOilCard/viewPapersDetails',
      payload: { id: id },
    });
    this.setState(
      {
        checkId: id,
        cardNo: cardNo,
      },
      () => {
        this.setState({
          visible: true,
        });
      }
    );
  };

  closeDetail = () => {
    this.setState({
      visible: false,
    });
  };
  getValue = values => {
    this.setState({
      cars: values,
    });
  };

  //启用、禁用：
  useVehicleType = (type, isSingle) => {
    const { dispatch } = this.props;
    const { checkIds, checkId } = this.state;
    let params = {};
    params.ids = isSingle ? [checkId] : checkIds;
    params.type = type == 'disabled' ? false : true;

    dispatch({
      type: 'tmsOilCard/ableOilCardOperate',
      payload: params,
      callback: res => {
        // prompt({ content: res.message });
        if (res.code == 0) {
          if (isSingle) {
            this.setState({
              vehicleAbled: type == 'disabled' ? false : true,
            });
            this.props.dispatch({
              type: 'tmsOilCard/selectDetails',
              payload: { id: checkId },
            });
          } else {
            this.props.dispatch({
              type: 'tmsOilCard/selectList',
              payload: { ...this.state.formValues },
            });
          }
        }
      },
    });
  };

  GoRechange = type => {
    const { checkIds, selectedRows, checkId, cardNo } = this.state;
    if (type == 'detail') {
      this.setState({
        visible: false,
        rechargeVisible: true,
      });
    } else {
      router.push({
        pathname: `/carBasic/oilCardList/recharge`,
      });
    }
  };
  handleCancel = e => {
    this.setState({
      rechargeVisible: false,
    });
  };
  handleRechargeOK = () => {
    this.child.operatePaneButton();
  };
  onRef = ref => {
    this.child = ref;
  };
  getChildValue = data => {
    if (data == 'false') {
      this.handleCancel();
    }
  };

  //删除
  removeRecord = () => {
    const { dispatch } = this.props;
    const { checkId, visible, formValues } = this.state;
    confirm({
      title: '确定要删除这条数据吗？',
      content: ' ',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'tmsOilCard/deleteOilCard',
          payload: { id: checkId },
          callback: () => {
            this.setState({ visible: false, selectedRows: [] });
            this.getSelectList(formValues);
          },
        });
      },
    });
  };
  render() {
    const {
      loading,
      tmsOilCard: { selectList, carList },
      form,
      isMobile,
      dictObject,
      ownCompany,
    } = this.props;
   // console.log('油卡——-dictObject',dictObject)
    const { getFieldDecorator } = form;
    const {
      selectedRows,
      updateModalVisible,
      stepFormValues,
      vehicleAbled,
      checkId,
      cardNo,
      visible,
      rechargeVisible,
      expandForm,
    } = this.state;
    const selectDetails =
      Object.keys(this.props.tmsOilCard.selectDetails).length > 0 && checkId
        ? this.props.tmsOilCard.selectDetails[checkId]
        : {};
    const vehicleAbled_check = vehicleAbled
      ? vehicleAbled
      : selectDetails && selectDetails.beActive;

    const firstFormItem = (
      <FormItem label="卡号">
        {getFieldDecorator('cardNo')(<Input placeholder="请输入卡号" />)}
      </FormItem>
    );
    const secondFormItem = (
      <FormItem label="发售公司">
        {getFieldDecorator('sellCompanyCode')(
          <Select placeholder="请选择" allowClear={true}>
            <Option value="">请选择</Option>
            {dictObject['sale-company'] &&
              dictObject['sale-company'].map(item => <Option key={item.code}>{item.value}</Option>)}
          </Select>
        )}
      </FormItem>
    );

    // secondForm 参数
    const otherFormItem = [
      [
        <FormItem label="车牌号">
          {getFieldDecorator('vehicleId')(
            // <Select
            //   allowClear={true}
            //   showSearch
            //   filterOption={(input, option) =>
            //     option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            //   }
            //   placeholder="请选择"
            //   style={{ width: '100%' }}
            // >
            //   <Option value="">请选择</Option>
            //   {carList &&
            //     carList.list &&
            //     carList.list.map((v, i) => {
            //       return (
            //         <Option key={i} value={v.id}>
            //           {v.cartPlateOneNo}
            //         </Option>
            //       );
            //     })}
            // </Select>
            <SearchSelect
              dataUrl="tms/tms-oil-card/selectOilVehicle"
              url="tms/tms-oil-card/selectOilVehicleView_s" // selectedData只只有id时需要传url
              selectedData={this.state.cars} // 选中值
              multiple={false} // 是否多选
              showValue="cartPlateOneNo"
              searchName="cartPlate"
              columns={columns1} // 表格展示列
              onChange={this.getValue} // 获取选中值
              scrollX={480}
              id="tmsOilCard_1"
            />
          )}
        </FormItem>,
      ],
      [
        <FormItem label="所属公司">
          {getFieldDecorator('ownCompanyId')(
            <Select
              allowClear={true}
              showSearch
              filterOption={(input, option) =>
                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
              placeholder="请选择"
              style={{ width: '100%' }}
            >
              <Option value="">请选择</Option>
              {ownCompany &&
                ownCompany.map((v, i) => {
                  return (
                    <Option key={i} value={v.customerCode}>
                      {v.customerName}
                    </Option>
                  );
                })}
            </Select>
          )}
        </FormItem>,
        <FormItem label="状态">
          {getFieldDecorator('beActive')(
            <Select placeholder="请选择" style={{ width: '100%' }} allowClear={true}>
              <Option value="">请选择</Option>
              <Option value="true">启用</Option>
              <Option value="false">禁用</Option>
            </Select>
          )}
        </FormItem>,
        'operatorButtons',
      ],
    ];
    const selectFormParams = {
      firstFormItem,
      secondFormItem,
      otherFormItem,
      form,
      code: codes.select,
      className: this.className,
      handleFormReset: this.handleFormReset,
      handleSearch: this.handleSearch,
      toggleForm: this.toggleForm,
    };
    const tableButtonsParams = {
      show: true,
      handleAdd: this.handleAdd,
      code: codes.add,
      buttons: (
        <Button.Group>
          <AdButton
            onClick={() => this.useVehicleType('disabled')}
            disabled={selectedRows.length > 0 ? false : true}
            text="禁用"
            code={codes.disable}
          />
          <AdButton
            onClick={() => this.useVehicleType('abled')}
            disabled={selectedRows.length > 0 ? false : true}
            text="启用"
            code={codes.enable}
          />
          <AdButton onClick={() => this.GoRechange()} text="充值" code={codes.rechage} />
        </Button.Group>
      ),
      selectedRows: selectedRows,
    };

    const rightDrawParams = {
      isMobile,
      visible,
      title: '油卡详情',
      code: codes.showDetail,
      closeDetail: this.closeDetail,
      buttons: (
        <span>
          <AdButton
            onClick={() => this.removeRecord(1)}
            text="删除"
            type="danger"
            code={codes.remove}
            ghost
          />
          <Button.Group style={{ marginLeft: 8 }}>
            {!vehicleAbled_check && (
              <AdButton
                onClick={() => this.useVehicleType('abled', 1)}
                text="启用"
                code={codes.enable}
              />
            )}
            {vehicleAbled_check && (
              <AdButton
                onClick={() => this.useVehicleType('disabled', 1)}
                text="禁用"
                code={codes.disable}
              />
            )}
            <AdButton onClick={() => this.GoRechange('detail')} text="充值" code={codes.rechage} />
            <AdButton onClick={this.handleEdit} type="primary" text="编辑" code={codes.edit} />
          </Button.Group>
        </span>
      ),
    };

    return (
      <Fragment>
        <SelectForm {...selectFormParams} />
        <TableButtons {...tableButtonsParams} />
        <StandardTable
          selectedRows={selectedRows}
          loading={loading}
          data={selectList}
          columns={this.columns}
          onSelectRow={this.handleSelectRows}
          onPaginationChange={this.handleStandardTableChange}
          expandForm={expandForm}
          className={this.className}
          code={codes.page}
        />
        <RightDraw {...rightDrawParams}>
          <OilCardDetails checkId={checkId} isMobile={isMobile} />
        </RightDraw>
        <Modal
          title={`油卡充值`}
          visible={rechargeVisible}
          onOk={this.handleRechargeOK}
          onCancel={this.handleCancel}
          width={720}
          style={{ top: 20 }}
        >
          <RechargeForm
            type="modal"
            onRef={this.onRef}
            oilCardId={checkId}
            cardNo={cardNo}
            pfn={this.getChildValue.bind(this)}
          />
        </Modal>
      </Fragment>
    );
  }
}
